<?php

namespace SLN0002\Service;

use Home\Common\FIdConst;
use Home\Service\BizlogService;
use Home\Service\PSIBaseExService;
use SLN0002\DAO\CADAO;

/**
 * 结账 Service
 *
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
class CAService extends PSIBaseExService
{
  private $LOG_CATEGORY = "结账";

  /**
   * 返回所有的公司列表
   *
   * @return array
   */
  public function companyList()
  {
    if ($this->isNotOnline()) {
      return $this->emptyResult();
    }

    $params = [
      "loginUserId" => $this->getLoginUserId(),
      "fid" => FIdConst::GL_CLOSE_ACC
    ];

    $dao = new CADAO($this->db());
    return $dao->companyList($params);
  }

  /**
   * 执行结账操作
   */
  public function actionCloseAcc($params)
  {
    if ($this->isNotOnline()) {
      return $this->notOnlineError();
    }

    $params["loginUserId"] = $this->getLoginUserId();
    $params["loginUserName"] = $this->getLoginUserName();
    $params["dataOrg"] = $this->getLoginUserDataOrg();

    $db = $this->db();

    $db->startTrans();
    $dao = new CADAO($db);

    $rc = $dao->actionCloseAcc($params);
    if ($rc) {
      $db->rollback();
      return $rc;
    }

    // 记录业务日志
    $log = $params["log"];
    $bs = new BizlogService($db);
    $bs->insertBizlog($log, $this->LOG_CATEGORY);

    $db->commit();

    return $this->ok();
  }

  /**
   * 结转损益
   */
  public function actionLossAndProfit($params)
  {
    if ($this->isNotOnline()) {
      return $this->notOnlineError();
    }

    $params["loginUserId"] = $this->getLoginUserId();
    $params["loginUserName"] = $this->getLoginUserName();
    $params["dataOrg"] = $this->getLoginUserDataOrg();

    $db = $this->db();

    $db->startTrans();
    $dao = new CADAO($db);

    $rc = $dao->actionLossAndProfit($params);
    if ($rc) {
      $db->rollback();
      return $rc;
    }

    // 记录业务日志
    $log = $params["log"];
    $bs = new BizlogService($db);
    $bs->insertBizlog($log, $this->LOG_CATEGORY);

    $db->commit();

    return $this->ok();
  }
}
